//
//  AlbumViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 5/23/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//  Dasdadasdas

#import "AlbumViewController.h"

#import "ParserClass.h"

#import "Album.h"

#import "AlbumTableViewCell.h"

#import "ParserClass.h"

#import "PostClass.h"

#import "UIManager.h"

#import "Songs.h"

#import "UserDetails.h"

#import "JsonClass.h"

#import "FTWAPI.h"

@interface AlbumViewController (){

    FTWAPI *ftwApi;
    
    NSArray *searchResults;
}

@end

@implementation AlbumViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
       // self.title = NSLocalizedString(@"Albums", @"");
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (!ftwApi) {
        ftwApi = [FTWAPI sharedInstance];
    }
    
    [self.navigationController setNavigationBarHidden:YES];
    
    [self.tableView setBackgroundColor:[UIColor colorWithRed:28/255.0 green:28/255.0 blue:28/255.0 alpha:1.0]];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelArtistFeeds" object:@"cancelArtist"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"cancelAlbums" object:nil];
    
    self.receivedData = [NSMutableData data];
    NSURLRequest *request = [[PostClass sharedItems] getAlbumsSchedsPhotos:[[ParserClass sharedItems] artistID]];
    _theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    [self setupPullToRefresh];
}

-(void)setupPullToRefresh
{
    
    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = self.tableView;
    
    _refreshControll = [[UIRefreshControl alloc] init];
    _refreshControll.tintColor = [UIColor redColor];
    //    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
    [_refreshControll addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = _refreshControll;
}

-(void)refreshTable{
    
    [self.tableView reloadData];
}



-(void) somethingHappens:(NSNotification*) notification
{
    NSLog(@"notification = %@",[notification object]);

    [self.theConnection cancel];
}


- (void)fetchedData:(NSData *)responseData {
    
    NSDictionary *json = [JsonClass jsonParser:responseData];
    
    if (json == nil) {
        UIAlertView *noSong = [[UIAlertView alloc] initWithTitle:@"" message:@"No Available Album" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [noSong show];
    }else{
    
    [[ParserClass sharedItems] albumDetails:json];
        
    [[ParserClass sharedItems] photos:json];
        
    [[ParserClass sharedItems] schedules:json];
    
    [self.tableView reloadData];
    }
    NSLog(@"albums = %@", json);
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger) buttonIndex
{
    if (buttonIndex == 0)
    {
        [self.tabBarController.navigationController popViewControllerAnimated:YES];
    }
}


-(void)userProfile{
    NSLog(@"User Profile 2");
    
    [self.tabBarController.navigationController popViewControllerAnimated:YES];
}

- (IBAction)backBtnAction:(id)sender{

    //[self.tabBarController.navigationController popViewControllerAnimated:YES];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}




- (void)viewWillAppear:(BOOL)animated{

    [self.tabBarController.tabBar setSelectionIndicatorImage:[UIImage imageNamed:@"albumTabClicked.png"]];
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [searchResults count];
        
    } else {
        return [[[ParserClass sharedItems] albumDetails] count];
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    
    if ([_refreshControll isRefreshing]) {
        [_refreshControll endRefreshing];
    }
    
    static NSString *cellIdentifier = @"Cell";
    
    AlbumTableViewCell *cell = (AlbumTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"AlbumTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    Album *album;
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        album = [searchResults objectAtIndex:indexPath.row];
    } else {
        album = [[ParserClass sharedItems] albumDetails][indexPath.row];
    }
    
    cell.albumLbl.text = [album albumName];
    
    //[cell setImageString:[NSString stringWithFormat:@"http://tapdashheuristics.com/projects/musicapp/backend-panel/%@",[album albumImg]]];
    
    [cell.lblNumberOfSongs setText:[NSString stringWithFormat:@"%@", [album songCount]]];
    
    @autoreleasepool {
        
        
        [cell.albumImg setAlpha:0];
        
        [UIView animateWithDuration:0.5 animations:^{
            
            NSString *imageUrl = [NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [album albumImg]];
            
            [ftwApi setupCoverImage:cell.albumImg withURL:imageUrl];
            [cell.activityView setHidden:YES];
            [cell.albumImg setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
    }
    
    
    
    return cell;
    
    
}


#pragma mark - Table view delegate

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    NSIndexPath *indexPaths = nil;
    Album *album = nil;
     UserDetails *user = [[ParserClass sharedItems] userDetails][0];
    
    if (self.searchDisplayController.active) {
        indexPaths = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
        album = [searchResults objectAtIndex:indexPaths.row];
        
        
    } else {
        indexPaths = [self.tableView indexPathForSelectedRow];
        album = [[ParserClass sharedItems] albumDetails][indexPaths.row];
    }
    
    [[ParserClass sharedItems] songDetails:[[PostClass sharedItems] getSong:[album artistAlbumID] andUserID:[user idUser]]];
    
    [[ParserClass sharedItems] getImgStr:[album albumImg]];
    
    [[ParserClass sharedItems] getAlbumName:[album albumName]];
    
    [[ParserClass sharedItems] getAlbumID:[album artistAlbumID]];
    
    [self.navigationController pushViewController:[[UIManager sharedItems] songsViewController] animated:YES];
  
}

- (void)viewDidUnload{
    
   // self.tableView = nil;
    [super viewDidUnload];
    
    [[ParserClass sharedItems] emptyAlbum];
}

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"albumName contains[c] %@", searchText];
    searchResults = [[[ParserClass sharedItems] albumDetails] filteredArrayUsingPredicate:resultPredicate];
    
     [self.tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    [self filterContentForSearchText:searchText
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
   
    NSLog(@"Searching = %@", searchText);

}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];
    //[self.tableView reloadData];
    NSLog(@"Searching = %@", searchString);
    
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 78;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [_receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error data = %@", error);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    
    if (connection == self.theConnection) {
        
        [_receivedData appendData:data];
        
        //  NSLog(@"data parse = %@", _receivedData);
        
    }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    if (connection == self.theConnection) {
        
        if (!(_receivedData == nil)) {
            
            NSLog(@"Count Confirmed");
            
            NSDictionary *json = [JsonClass jsonParser:_receivedData];
       
                [[ParserClass sharedItems] albumDetails:json];
                
                [[ParserClass sharedItems] photos:json];
                
                [[ParserClass sharedItems] schedules:json];
                
                [self.tableView reloadData];
      
            NSLog(@"albums = %@", json);
            
            
        }
        
        
        NSLog(@"Finish");
    }
    
}


- (void)searchDisplayController:(UISearchDisplayController *)controller didLoadSearchResultsTableView:(UITableView *)tableView {
    tableView.backgroundColor = [UIColor blackColor];
    
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
}

@end
